const { invoke } = window.__TAURI__.core;


// 元素引用  
const openZipBtn = document.getElementById('open-zip');  
const compressBtn = document.getElementById('compress');  
const showTimeCheckbox = document.getElementById('show-time');  
const showDebugCheckbox = document.getElementById('show-debug');  
const showIgnoreCheckbox = document.getElementById('show-ignore'); 
const searchSeamInput = document.getElementById('search-seam');  
const searchBtn = document.getElementById('search');  
const logList = document.getElementById('log-list');  
const logContent = document.getElementById('logCode');  
const loadingSpinner = document.getElementById('loadingSpinner');  

let selectedLi = null; // 用于跟踪当前选中的列表项 

let logCache = {};
let seamNames = []; // 存储焊缝名称
let seamNamesIDs = []; // 存储焊缝名称
let currentLogName = null; // 用于存储当前显示的日志文件名 
let showTime = true, showDebug = true ,showIgnore = false;

// 函数用于更新行号  
const updateLineNumbers = (_content) => {  
    const lineNumbers = document.querySelector('.line-numbers');  
    const lineNumbersCount = lineNumbers? lineNumbers.children.length:0; 
    const lines = _content.split('<br/>');
    const lineCount = lines.length - 1;

    if(lineCount !== lineNumbersCount){
        let lineNumberHTML = '';
        for (let i = 0; i < lineCount; i++) {
            lineNumberHTML += `${i + 1}. `;
        }
        lineNumbers.innerHTML = lineNumberHTML;
    }

    console.log(lineCount,lineNumbersCount);
};  

// 使用 MutationObserver 监听 #log-content 的变化  
const observeLogContent = () => {  
    const lineNumbers = document.querySelector('.line-numbers');  
    if (!logContent) {  
        console.error("日志内容容器（#log-content）未找到");  
        return;  
    }  
    console.debug("开始监听");

    const spinner = openZipBtn.querySelector('.spinner-container');  

    openZipBtn.addEventListener('mouseenter', () => {  
        spinner.style.display = 'inline-block'; // 鼠标悬停时显示 spinner  
    });  

    openZipBtn.addEventListener('mouseleave', () => {  
        spinner.style.display = 'none'; // 鼠标离开时隐藏 spinner  
    });  


    logContent.addEventListener('scroll',(event) => {  
      console.debug("scrollTop:",logContent.scrollTop) ;
      lineNumbers.scrollTop = logContent.scrollTop; 
    });
};  




window.addEventListener('DOMContentLoaded', () => {  
    observeLogContent();  
});  

// 创建一个休眠函数  
function sleep(ms) {  
    return new Promise(resolve => setTimeout(resolve, ms));  
} 

// 打开 Zip 文件  
openZipBtn.addEventListener('click', async () => {  
    try{
        
        const filePath = await invoke('open_zip'); 
        loadingSpinner.style.display = 'block';  
        sleep(40000); 
        if (filePath) {  
            logCache = {}; // 清空缓存  
            seamNames = []
            seamNamesIDs = {}
            await  loadLogs();  
        }  
    }catch (error) {  
        console.error('Error opening zip file:', error);  
    } finally {  
        // 隐藏进度条  
        loadingSpinner.style.display = 'none';  
    }  
    loadingSpinner.style.display = 'none';  
});  



// 加载并显示日志  
async function loadLog(logName) {  
    if (logCache[logName]) {  
        let vv = await translateHtml(logCache[logName])
        displayLog(vv);
        currentLogName = logName;  
    } else {  
        console.error("Log名称不存在:",logName);
        alert("Log名称不存在:",logName);
    }  
    
  }  
  

async function loadLogs() {  
    const logs = await invoke('get_ori_logs');
    for (const [key, value] of Object.entries(logs.logs)) {  
        logCache[key] = value;
        await extractSeamNames(key,value); 
    };    
    displayLogList(logs.logs);  
    
} 

// 整合信息  
compressBtn.addEventListener('click', async () => {  

});  

// 显示/隐藏时间  
showTimeCheckbox.addEventListener('change', (event) => { 
    showTime  = event.target.checked;  
    loadLog(currentLogName);
});  


showDebugCheckbox.addEventListener('change', async(event) => {  
    showDebug = event.target.checked;    
    loadLog(currentLogName);
});

showIgnoreCheckbox.addEventListener('change', async(event) => {  
    showIgnore = event.target.checked;    
    loadLog(currentLogName);
});


// 搜索焊缝  
searchBtn.addEventListener('click', async () => {  
    const seam = searchSeamInput.value.trim();  
    if (seam === '') {  
        alert('请输入要查找的焊缝名称');  
        return;  
    } else{
        const hasKey = seam in seamNamesIDs;
        if(seamNames.includes(seam) && hasKey){
            console.debug('To display->',seam);
            console.debug('To display->',seamNamesIDs[seam]);
            loadLog(seamNamesIDs[seam]);
        }
    }
  
});  

function displayLogList(logs) {  
    logList.innerHTML = '';  
    for (const [logName, logDisplay] of Object.entries(logs)) {  
            const li = document.createElement('li');  
            li.className = 'list-group-item'; // 添加 Bootstrap 样式  
            li.textContent = logName;  

            li.addEventListener('click', async () => {  
                await loadLog(logName);  //
                if (li.tagName === 'LI') {  
                    // 如果已经有选中的 <li>，移除其选中类  
                    if (selectedLi) {   
                        selectedLi.classList.remove('active'); 
                    }  

                    // 给当前点击的 <li> 添加选中类  
                    li.classList.add('active');
                    selectedLi = li; 
                }  
        });  
        logList.appendChild(li);  
    }  
}  



// 显示日志内容  
function displayLog(htmlContent) {  
    const startTime = performance.now();
    // logContent.innerHTML = htmlContent;  xs
    logContent.innerHTML =   htmlContent;
    // logContent.textContent = htmlContent; 
    updateLineNumbers(htmlContent); // 重新生成行号 
    const endTime = performance.now();
    console.debug(`displayLog执行耗时：${endTime - startTime} 毫秒`);
    console.debug("HTML:",htmlContent);
}

function isDarkMode() {  
    // 从 localStorage 获取存储的主题  
    const storedTheme = localStorage.getItem('theme');  

    // 如果存储有主题值，判断其是否为 'dark'  
    if (storedTheme) {  
        return storedTheme === 'dark'; // 如果是 'dark' 返回 true，否则返回 false  
    }  
    // 使用 matchMedia 检查首选的颜色模式  
    return window.matchMedia('(prefers-color-scheme: dark)').matches; // 返回 true 如果为夜间模式  
}

async function translateHtml(content) {  
    const lines = content.html.split('\n');   
    let html = '';  

    // 定义用于解析的正则表达式  
    const regex = /\[(\d{2}:\d{2}:\d{2}\.\d{3})\]\[(info|warn|error|debug)\]:?(?:\s*\[(suc|fail|ignore)\])?(.*)/;  


    // 检查当前主题  
    const isDark = isDarkMode();  
    

    for (const line of lines) {  
        // 去除多余的空格  
        const trimmedLine = line.trim();  
        if (trimmedLine === '') continue; // 跳过空行  

        const match = regex.exec(trimmedLine);  
        if (!match) continue; // 如果这一行不匹配日志格式，跳过  

        const timestamp = match[1] || '';  
        const level = match[2] || '';  
        const prefix = match[3] || '';  
        const message = match[4] ? match[4].trim() : '';  

        let color = isDark ? 'lightgray' : 'black'; // 默认文本颜色  
        let backgroundColor = '#00000000'; // 背景颜色 
        if(isDark) {
            color = 'lightgray';
        }else{
            color = 'black';
        }
   
        switch (level) {  
            case 'info':  
                color = isDark ? 'lightgray' : 'black';  
                break;  
            case 'warn':  
                color = isDark ? 'orange' : 'darkorange';  
                break;  
            case 'error':  
                color = isDark ? 'red' : 'darkred';  
                break;  
            case 'debug':  
                color = isDark ? 'cyan' : 'blue';  
                if (!showDebug) {  
                    continue;  
                }  
                break;  
            default:  
                break;  
        }  

        if (prefix === 'suc') {  
            color = isDark ? 'lightgreen' : 'green';  
        } else if (prefix === 'fail') {  
            color = isDark ? 'lightcoral' : 'red';  
        }  else if (prefix === 'ignore') {  
            color = isDark ? 'lightgreen' : 'green';  
            if (!showIgnore) {  
                continue;  
            } 
        }  


        const displayTimestamp = showTime ? `[${timestamp}] ` : '';  

        // 使用 HTML 标签设置文本颜色并添加到 QTextBrowser  
        const logEntry = `<span style="color: ${color}; background-color: ${backgroundColor};">${displayTimestamp}${message}</span><br/>`;  
        html += logEntry;  
    }  
    return html;  
}

// 从日志的前10行提取焊缝名称  
async function extractSeamNames(key,lcntent) {  
    let logCC = lcntent.html;
    const lines = logCC.split('\n');  
    for (let i = 0; i < Math.min(lines.length, 10); i++) {  
        const line = lines[i];  
        const match = line.match(/##(.+?)##/);  
        
        if (match) {  
            seamNames.push(match[1]); // 提取焊缝名称并存入数组  
            seamNamesIDs[match[1]] = key;
        }  
    }  
}  


// 更新建议列表  
function updateSuggestions(input) {  
    const suggestionList = document.getElementById('suggestion-list');  
    suggestionList.innerHTML = ''; // 清空之前的建议  
    const keyword = input.value.toLowerCase();  
    

    seamNames.forEach(seam => {  
        if (seam.toLowerCase().includes(keyword)) { // 检查焊缝名称是否包含关键字  
            const li = document.createElement('li');  
            li.textContent = seam;  
            li.classList.add('list-group-item');  
            li.addEventListener('click', () => {  
                input.value = seam; // 点击时将焊缝名称填入输入框  
                suggestionList.innerHTML = ''; // 清空建议  
            });  
            suggestionList.appendChild(li);  
        }  
    });  

    // 设置建议列表显示  
    suggestionList.style.display = suggestionList.childElementCount ? 'block' : 'none'; // 仅在有建议时显示
}  

// 监听输入框的输入事件  
document.getElementById('search-seam').addEventListener('input', function() {  
    updateSuggestions(this); // 传入当前输入框  
});  

// 点击输入框时清空建议列表  
document.getElementById('search-seam').addEventListener('focus', function() {  
    const suggestionList = document.getElementById('suggestion-list');  
    suggestionList.innerHTML = ''; // 清空建议  
});  